package com.xlzcx.xltz.controller;


import com.xlzcx.xltz.entity.vo.AUserVo;
import com.xlzcx.xltz.filter.SkipLogin;
import com.xlzcx.xltz.service.a_user.AUserService;
import com.xlzcx.xltz.utils.EmailUtil;
import com.xlzcx.xltz.utils.R;
import com.xlzcx.xltz.utils.RedisUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.regex.Pattern;

/**
 * 作者: 李咨辰
 * 文件名: AUserController.java
 * 路径: com.xlzcx.xltz.controller
 * 时间: 2024-10-05 11:31
 * 版本: 1.0
 * 描述: TODO 用户
 **/
@RestController
@RequestMapping("/user")
public class AUserController {

    /**
     * 调用业务层
     */
    @Resource
    private AUserService aUserService;


    /**
     * 登录方法
     *
     * @param map     账号、密码
     * @param request 用于设置session
     * @return 登录对象
     */
    @SkipLogin
    @PostMapping("/doLogin")
    public R doLogin(@RequestBody HashMap<String, String> map, HttpServletRequest request) {
        AUserVo aUser = aUserService.doLogin(map, request);
        if (aUser == null) {
            return R.ok().put("data", "账号或密码错误");
        }
        request.getSession().setAttribute("user", aUser);
        return R.ok().put("data", aUser);
    }

    /**
     * 登录状态验证
     *
     * @param map     id、授权码
     * @param request 用于设置session
     * @return 登录对象
     */
    @SkipLogin
    @PostMapping("/loginStatus")
    public R loginStatus(@RequestBody HashMap<String, String> map, HttpServletRequest request) {
        AUserVo aUser = aUserService.loginStatus(map.get("id"), map.get("secret"), request);
        if (aUser == null) {
            request.getSession().removeAttribute("user");
            return R.ok().put("data", null);
        }
        request.getSession().setAttribute("user", aUser);
        return R.ok().put("data", aUser);
    }


    /**
     * 注册
     *
     * @param map     账号、密码、验证码
     * @param request 用于获取ip地址
     * @return json响应码
     */
    @SkipLogin
    @PostMapping("/signIn")
    public R singIn(@RequestBody HashMap<String, String> map, HttpServletRequest request) {
        String user = map.get("user");
        String password = map.get("password");
        String code = map.get("code");
        String redis_code = RedisUtil.get("captcha:" + user);
        if (!code.equals(redis_code)) {
            return R.ok().put("data", "验证码不正确");
        }
        //清除redis缓存
        RedisUtil.delKey("captcha:" + user);
        //判断用户是否注册
        if (aUserService.getUserByPhoneOrEmail(user)) {
            //注册账号
            if (aUserService.singIn(user, password, request) > 0) {
                return R.ok().put("data", "注册成功，请返回登录！");
            }
            return R.ok().put("data", "注册失败！");
        }
        return R.ok().put("data", "邮箱或手机号已被注册！");
    }

    /**
     * 获取验证码
     *
     * @param map 邮箱或手机号
     * @return json响应码
     */
    @SkipLogin
    @PostMapping("/captCha")
    public R captCha(@RequestBody HashMap<String, String> map) {
        String user = map.get("user");
        if (null != RedisUtil.get("captcha:" + user)) {
            return R.ok().put("data", "验证码已发送，请稍后重试！");
        }
        String captcha = String.valueOf((int) ((Math.random() * 9000) + 1000));

        if (Pattern.matches("^1[3-9]\\d{9}$", user)) {//手机号
            //手机号
            System.out.println("======================================================");
            System.out.println("======================================================");
            System.out.println("======================================================");
            System.out.println("手机号验证码:" + captcha);
            System.out.println("======================================================");
            System.out.println("======================================================");
            System.out.println("======================================================");
        } else if (Pattern.matches("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$", user)) {
            //邮箱
            EmailUtil emailUtil = new EmailUtil("czhgongsi@sina.com", "98739c13be079a35", "smtp.sina.com", "465");
            StringBuilder emailText = new StringBuilder();
            emailText.append("<div style='max-width:600px;margin:auto;background-color:#ffffff;padding:20px;border-radius:")
                    .append("8px;'>")
                    .append("<p style='font-size:16px;color:#666666;'>感谢您使用我们的服务！您的验证码如下，请在5分钟内输入：</p>")
                    .append("<p style='font-size:24px;font-weight:bold;color:#ffffff;background-color:")
                    .append("#4CAF50;padding:5px 20px;border-radius:5px;display:inline-block;'>")
                    .append("<span style='text-decoration:none;color:inherit;'>")
                    .append(captcha)
                    .append("</span></p>")
                    .append("<p style='font-size:16px;color:#666666;'>如果该验证码不是您本人申请，请立即修改您的账号密码！</p>")
                    .append("<p style='font-size:16px;color:#666666;'>祝您愉快！</p>")
                    .append("<div style='margin-top:20px;font-size:12px;color:#aaaaaa;'><p>此邮件由系统自动生成，请勿回复。</p></div>");
            emailUtil.sendAMessage("XXX平台", user, "请查收您的验证码", emailText.toString(), true, "to");
        } else {
            //无效
            return R.ok().put("data", "请输入正确的手机号或验证码");
        }
        //将信息存入redis
        RedisUtil.set("captcha:" + user, captcha);
        //设置过期时间为300秒
        RedisUtil.expire("captcha:" + user, 300);
        return R.ok().put("data", "验证码发送成功，请注意查收");
    }

    /**
     * 修改用户
     *
     * @param aUser 用户类
     * @return 成功返回true
     */
    @PostMapping("/editUser")
    public R editUser(@RequestBody AUserVo aUser, HttpServletRequest request) {
        boolean editUser = aUserService.editUser(aUser, request);

        return R.ok().put("data", editUser);
    }


}
